package com.jzmy.specialist.controller;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.commons.entity.*;
import com.example.commons.utils.ApiEnumError;
import com.example.commons.utils.ApiResult;

import com.example.commons.utils.JWTUtil;
import com.jzmy.specialist.config.RedisUtil;
import com.jzmy.specialist.entity.*;
import com.jzmy.specialist.entity.util.DeduplicationUtil;
import com.jzmy.specialist.entity.util.UrlUtil;
import com.jzmy.specialist.entity.vo.ExpertsApiVo;
import com.jzmy.specialist.entity.vo.ExpertsVo;
import com.jzmy.specialist.entity.vo.MyExpertsVo;
import com.jzmy.specialist.feign.*;
import com.jzmy.specialist.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.commons.utils.TokenTag.TOKEN_TAG;

/**
 * @author mengzhichao
 * @create 2022-08-23-15:21
 */
@RestController
@RequestMapping("/experts")
@Slf4j
public class ApiExpertsController {

    @Autowired
    private ExpertsService expertsService;

    @Autowired
    private KnowledgePointsService knowledgePointsService;


    @Autowired
    private OrganizationNewsService organizationNewsService;


    @Autowired
    private UserOpenfeign userOpenfeign;

    @Autowired
    private ResumesOpenFeign resumesOpenFeign;

    @Autowired
    private TrainingCertificatesService trainingCertificatesService;

    @Autowired
    private CoursesOpenFeign coursesOpenFeign;

    @Autowired
    private CertificateProfileOpenFeign certificateProfileOpenFeign;

    @Autowired
    private RoleOpenfeign roleOpenfeign;

    @Autowired
    private honorUserOpenFeign onorUserOpenFeign;

    @Resource
    private RedisUtil redisUtil;



    /**
     * api小程序端-专家列表数据接口
     *
     * @Description: 专家列表信息查询，参数：页码，显示数，站点名称（筛选条件），站点类型 （0考评员，1考务员，2考务技术员，3督导员，4讲师）
     * @Param: [current, number, name, type]
     */
    @GetMapping("/selExperts")
    @Transactional
    public ApiResult<?> selExperts(String current, String number, String name, String newType, String id,String newType1and2,String orgName) {
        Map map = new HashMap();

        if(StringUtils.isNotBlank(id)){
            map.put("id",id);
        }
        if(StringUtils.isNotBlank(name)){
            map.put("name",name);
        }
        if(StringUtils.isNotBlank(newType)){
            map.put("newType",Integer.parseInt(newType));
        }

        if (StringUtils.isNotBlank(newType1and2)){
            map.remove("newType");
            map.put("newType1and2",1);
        }
        if(StringUtils.isNotBlank(orgName)){
            map.put("orgName",orgName);
        }

        Map parameterMap =new HashMap();
        parameterMap.put("current",current);
        parameterMap.put("number",number);
        parameterMap.put("name",name);
        parameterMap.put("newType",newType);
        parameterMap.put("id",id);
        parameterMap.put("newType1and2",newType1and2);
        parameterMap.put("orgName",orgName);

        String key = redisUtil.createRediskey(parameterMap, "selExperts");
        System.out.println("专家接口生成的key为："+key+"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        Page<ExpertsVo>  ca = (Page<ExpertsVo>) redisUtil.get(key);
        if (ca != null){
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++专家列表数据接口进入缓存");
            return ApiResult.success(ca);
        }

        Page<ExpertsVo> page = expertsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExpertsVo obj = (ExpertsVo) page.getRecords().get(i);
            if (obj.getKpointsId() != null) {
                KnowledgePoints knowledgePointsDO = knowledgePointsService.getById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    obj.setKpointsName(knowledgePointsDO.getName());
                }
            }
            if (obj.getHeadPortrait()!=null){
                boolean urlValid = UrlUtil.isUrlValid(obj.getHeadPortrait());
                if (!urlValid){
                    obj.setHeadPortrait(""); //如果不为true代表链接失效直接置空即可
                }
            }

            if (obj.getProfileId() != null){
                String profile = certificateProfileOpenFeign.selByFormalByProfileId(obj.getProfileId());
                if (profile != null) {
                    obj.setProfileId(profile);
                }
            }
            list.add(obj);
        }
        List<ExpertsVo> expertsVoList = (List<ExpertsVo>) list.stream()
                .filter(DeduplicationUtil.distinctByKey(ExpertsVo::getUserId))
                .collect(Collectors.toList());
        page.setRecords(expertsVoList);
        redisUtil.set(key,page,86400); //一天过期
        return ApiResult.success(page);
    }





    /**
     * api小程序端-专家申请接口
     *
     * @Description: 专家信息申请，填入数据库；参数：Token令牌，专家照片，附件路径，邮箱，专家姓名，专家性别，专家身份证号，专家类型，所属单位，知识点Id，
     * 证书概况id，出生年月，民族，学历，专业，政治面貌，职务职称，QQ，学习、工作经历，现居住地,省份，市，区
     */
    @PostMapping("/saveCaoExpert")
    @RequiresAuthentication
    @Transactional
    public ApiResult<?> saveCaoExpert(@RequestHeader(value = "Authorization", required = false) String token,@RequestBody ExpertsApiVo expertsApiVo) {
        //1.根据token获取用户登录数据
        UserDO user = userOpenfeign.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }
        boolean isInsert=false;

        if ("特聘专家".equals(expertsApiVo.getNewType())){
            expertsApiVo.setNewType("1");
        }
        if ("师资队伍".equals(expertsApiVo.getNewType())){
            expertsApiVo.setNewType("2");
        }
        if ("考评专家".equals(expertsApiVo.getNewType())){
            expertsApiVo.setNewType("3");
        }

        Experts experts = expertsService.findOneByKv("type",Integer.parseInt(expertsApiVo.getNewType()),"user_id",user.getId(),"profile_id", Long.parseLong(expertsApiVo.getProfileId()));
        if (experts != null) {
            if(experts.getState()!=6) {
                //提示已申请
                return ApiResult.build(ApiEnumError.EnrolmentError.getCode(), "已申请");
            }
        }else{
            experts = new Experts();
            isInsert=true;
        }


        if(user.getOrgId() != null){
            experts.setOrgId(user.getOrgId());
        }else{
            // 2020-03-12新增逻辑-kl
            // 查询判断机构是否在系统内存在： 如不存在，则只在用户表中存入机构信息； 如存在，则存入机构id
            QueryWrapper<OrganizationNews> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name", expertsApiVo.getOrgName());
            List<OrganizationNews> organizationNewsList = organizationNewsService.list(queryWrapper);
            if (CollectionUtils.isEmpty(organizationNewsList)) { // 无机构，则机构信息错误
                return ApiResult.build(ApiEnumError.orgsErr.getCode(), ApiEnumError.orgsErr.getMsg());
            } else if (organizationNewsList.size() > 1) { // 多机构，则机构信息不全
                return ApiResult.build(ApiEnumError.orgsIncompleteInfo.getCode(), ApiEnumError.orgsIncompleteInfo.getMsg());
            } else {
                experts.setOrgId(organizationNewsList.get(0).getId());//机构id
                user.setOrgId(organizationNewsList.get(0).getId());
            }

        }


        //4.更新用户表信息
        if(StringUtils.isBlank(user.getName())){
            user.setName(expertsApiVo.getName());//真实姓名
        }

        if(StringUtils.isBlank(user.getOrgName())){
            user.setOrgName(expertsApiVo.getOrgName());//所属机构名称
        }
        if(user.getSex() == null){
            user.setSex(Long.parseLong(expertsApiVo.getSex()));//性别
        }else if(user.getSex() == 0){
            user.setSex(Long.parseLong(expertsApiVo.getSex()));//性别
        }
        if(StringUtils.isBlank(user.getIdNumber())){
            user.setIdNumber(expertsApiVo.getIdNumber());//身份证号码
        }

        if(StringUtils.isBlank(user.getQQ())){
            user.setQQ(expertsApiVo.getQQ());//QQ
        }
        if(StringUtils.isBlank(user.getEmail())){
            user.setEmail(expertsApiVo.getEmail());//邮箱
        }
        if(StringUtils.isBlank(user.getNation())){
            user.setNation(expertsApiVo.getNation());//民族
        }
        if(StringUtils.isBlank(user.getEducation())){
            user.setEducation(expertsApiVo.getEducation());//学历
        }
        if(StringUtils.isBlank(user.getMajor())){
            user.setMajor(expertsApiVo.getMajor());//专业
        }
        if(StringUtils.isBlank(user.getPoliticalAffiliation())){
            user.setPoliticalAffiliation(expertsApiVo.getPoliticalAffiliation());//政治面貌
        }
        if(StringUtils.isBlank(user.getOfficialCapacity())){
            user.setOfficialCapacity(expertsApiVo.getOfficialCapacity());//职务职称
        }

        if(StringUtils.isBlank(user.getExperience())){
            user.setExperience(expertsApiVo.getExperience());//学习、工作经历
        }
        if(StringUtils.isBlank(user.getLiveAddress())){
            user.setLiveAddress(expertsApiVo.getLiveAddress());//通讯地址
        }
        if(StringUtils.isBlank(user.getProvince())){
            user.setProvince(expertsApiVo.getProvince());//省份
        }
        if(StringUtils.isBlank(user.getCity())){
            user.setCity(expertsApiVo.getCity());//市
        }
        if(StringUtils.isBlank(user.getDistrict())){
            user.setDistrict(expertsApiVo.getDistrict());//区
        }

        if(StringUtils.isBlank(user.getDateOfBirth())){
            user.setDateOfBirth(expertsApiVo.getDateOfBirth());//出生年月
        }

        //if(j){
        List<Long> roleIds = userOpenfeign.listRoleId(String.valueOf(user.getId()));
        if (roleIds != null && roleIds.size() > 0) {
            user.setRoleIds(roleIds);
        } else {
            List<Long> list = new ArrayList<>();
            list.add(56L);
            user.setRoleIds(list);
        }
        boolean c = userOpenfeign.userUpdateById(user);
        if (c) {
            experts.setName(expertsApiVo.getName());//专家姓名

            experts.setKpointsId(null);//知识点id
            experts.setNewType(Integer.parseInt(expertsApiVo.getNewType()));//专家类型
            experts.setApplicantDate(new Date());//申请时间
            experts.setUserId(user.getId());//会员id
            experts.setProfileId(Long.parseLong(expertsApiVo.getProfileId()));//证书概况id
            experts.setEnclosure(expertsApiVo.getFileUrl());//附件路径
            experts.setHonor(expertsApiVo.getHonor());//附件路径
            experts.setState(6);
            if(isInsert){
                expertsService.save(experts);
            }else{
                expertsService.updateById(experts);
            }
            return ApiResult.success();
        } else {
            return ApiResult.fail();
        }
    }




    @GetMapping("/selMyCer")
    public ApiResult<?> selMyCer(@RequestHeader(value = "Authorization",required = false) String token , Integer current , Integer number){
        UserDO user = this.userOpenfeign.getUser();
        if (user == null){
            return ApiResult.invalid();
        }

        Page<TrainingCertificates> page = trainingCertificatesService.findPageList(current , number , user.getId());
        List<TrainingCertificates> traList = page.getRecords();

        for (TrainingCertificates training : traList){
            CoursesDO courses = coursesOpenFeign.selectById(training.getCoursesId());
            if (courses != null){
                training.setCoursesName(courses.getName());
            }

            training.setUserName(user.getName());
        }

        return ApiResult.success(page);
    }



    @GetMapping("/selResume")
    public ApiResult<?> selResume(){
        UserDO user =  JWTUtil.getUser();
        if (user == null){
            return ApiResult.invalid();
        }
        Resumes resumes = resumesOpenFeign.findOneByKv("user_id" ,user.getId());
        Map map = new HashMap();
        if (resumes != null){
            if ( StringUtils.isNotBlank(resumes.getWorkExperience()) && StringUtils.isNotBlank(resumes.getSelfEvaluation())
                 && StringUtils.isNotBlank(resumes.getGraduatedFrom()) && StringUtils.isNotBlank(resumes.getSelfEvaluation())
                    &&StringUtils.isNotBlank(resumes.getEducationExperience())
            ){
                map.put("state" , 0);

                return ApiResult.success(map);
            }else {
                map.put("state" , -1);
                return ApiResult.success(map);
            }

        }else {
            map.put("state" , -1);
            return ApiResult.success(map);
        }
    }


    /**
     * 我的证书
     * @return
     */
    @GetMapping("/getUserCertificate")
    public ApiResult<?> getUserCertificate(){
        UserDO user = JWTUtil.getUser();
        if (user == null){
            return ApiResult.invalid();
        }
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.in("user_id",user.getId());
        queryWrapper.in("state",0); //证书状态为正常0
        List<TrainingCertificates> list = trainingCertificatesService.list(queryWrapper);
        for (int i=0;i<list.size();i++){
            list.get(i).setUserName(user.getUsername());
        }
        return ApiResult.success(list);
    }



    /**
     * api小程序端-证书概况信息列表接口--公开方法，不需要登录
     *
     * @Description: 查询证书概况信息列表
     * @Param: []
     */
    @GetMapping("/selProfileFill")
    @Transactional
    public ApiResult<?> selProfileFill() {
        List<Map<Object, Object>> maps = certificateProfileOpenFeign.selByFormal();
        return ApiResult.success(maps);
    }

    /**
     * api小程序端-查询对应证书的知识点--公开方法，不需要登录
     */
    @GetMapping("/findKonwledge")
    public ApiResult<?> findKonwledge(String profileId) {
        List<KnowledgePoints> knowList = knowledgePointsService.findByKv("profile_id", profileId, "state", 0);
        return ApiResult.success(knowList);
    }


    /**
     * api小程序端-获取用户信息
     */
    @GetMapping("/selUserDetail")
    @RequiresAuthentication
    public ApiResult<?> selUserDetail() {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        } else {
            user.setRoleNameList(getRoleNamesToken(user.getId()));
            HonorUserDO honorUserDO=onorUserOpenFeign.findOneByKv("mobile",user.getMobile());
            if(honorUserDO!=null){
                user.setHonorImageSrc(honorUserDO.getHonorImageSrc());
            }else {
                TrainingCertificates url=  trainingCertificatesService.findOneByKv("user_id",user.getId());
                if(url!=null&&"0".equals(url.getState())){
                    user.setHonorImageSrc(url.getImgUrl());
                }

            }

            return ApiResult.success(user);
        }
    }

    public String getRoleNamesToken(Long userId) {
        String roleName = "";
        List<UserRoleDO> userRole = userOpenfeign.findByKv("userId", userId);
        if (userRole != null && userRole.size() > 0) {
            for (UserRoleDO roleDO : userRole) {
                RoleDO role = roleOpenfeign.getById(roleDO.getRoleId());
                roleName = roleName + role.getRoleName() + ",";
            }
        }
        return roleName;
    }



    /**
     * api小程序端-我的专家申请记录接口
     *
     * @Description: 小程序登录后，查询专家申请记录；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     */
    @GetMapping("/selMyExpertsList")
    public ApiResult<?> selMyExpertsList(String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<MyExpertsVo> page = expertsService.selByUserId(Integer.parseInt(current), Integer.parseInt(number), user.getId());
        return ApiResult.success(page);
    }


}
